﻿<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>4.AJAX返回</title>
    <script type="text/javascript" src="../Content/highlighter/scripts/shCore.js"></script>
    <script type="text/javascript" src="../Content/highlighter/scripts/shBrushCSharp.js"></script>
    <script type="text/javascript" src="../Content/highlighter/scripts/shBrushXml.js"></script>
    <link type="text/css" rel="stylesheet" href="../Content/highlighter/styles/shCoreDefault.css"/>
    <script type="text/javascript">SyntaxHighlighter.all();</script>
</head>
<body>
	<h3>AJAX返回</h3>
	<p>
		NFinal默认ajax结构{"code":1,"msg":"添加成功!","data":null}
	</p>
    <p>
        我们经常会用到ajax,当我们想返回以上json时,需要这样写.
    </p>
    <pre class="brush: csharp;">
        context.Response.ContentType="application/json";
        context.Response.Write("{");
        context.Response.Write("\"code\":0,");
        context.Response.Write("\"msg\":\"添加成功!\"");
		context.Response.Write("\"data\"","null");
        context.Response.Write("}")
        context.Response.End();
    </pre>
    <p>这样做很不方便.我们可以直接在控制器中这样写.
    </p>
    <pre class="brush: csharp;">
		//返回{"code":1,"msg":"","data":{"id":1}}
        this.AjaxReturn("{\"id\":1}");
		//返回{"code":2,"msg":"","data":{"id":1}}
        this.AjaxReturn("{\"id\":1}", 2);
		//返回{"code":1,"msg":"添加成功","data":{"id":1}}
        this.AjaxReturn("{\"id\":1}",1,"添加成功");
		//返回{"code":1,"msg":"添加成功","data":null}
        this.AjaxReturn(1, "添加成功");
		//当然也可以使用这个,其中obj为任意类型
		//返回{"code":2,"msg":"","data":【obj序列化的json字符串】}
		this.AjaxReturn(obj);
    </pre>
    <p>
        另外json的组装也很麻烦.NFinal包含了LitJson框架,用于处理Json.
        LitJson的详细用法,可以百度一下.这里只是给一个小例子:
    </p>
      由于LitJson速度远远超过Newtonsoft.Json，<br/>
	  建议使用JsonData来解析或生成json:
    <pre class="brush: csharp;">
        LitJson.JsonData data = new LitJson.JsonData();
        data["name"] = "peiandsky";
        data["age"] = 28;
        data["sex"] ="male";
        //{"name":"peiandsky","age":28,"sex":"male"}
        string json= data.ToJson();
    </pre>
</body>
</html>
